package no.spk.util.inforama;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
 * @author Marius Breivik - Accenture
 */
public class ArchiveEntryAnalyzer {

	private WebArchive webArchive;
	private static final String name = "pom.properties";

	public ArchiveEntryAnalyzer() {
	}

	public void analyzeWebArchive(WebArchive archive) {
		this.webArchive = archive;
		try {
			archive.getArchiveProperties().load(analyze());
		} catch (IOException e) {
			e.printStackTrace();
		}
		webArchive.setArchiveVersion(webArchive.getArchiveProperties().getProperty("version"));
		webArchive.setArchiveArtifactId( webArchive.getArchiveProperties().getProperty("artifactId"));
		webArchive.setArchiveGroupId( webArchive.getArchiveProperties().getProperty("groupId") );
	}

	private InputStream analyze() {
		ZipInputStream zin = null;
		try {
			InputStream root = new BufferedInputStream(new FileInputStream(webArchive.getArchivePath()));
			zin = new ZipInputStream(root);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} 
		return find(zin, name);
	}

	private boolean isArchive(String name) {
		String s = name.toLowerCase();
		return s.endsWith(".war");
	}

	private InputStream find(ZipInputStream in, String name) {
		ZipEntry entry;
		try {
			while ((entry = in.getNextEntry()) != null) {
				String entryName = entry.getName();

				if (entryName.endsWith(name)) {
					return in;
				}

				if (isArchive(entryName)) {
					InputStream result = find(new ZipInputStream(in), name);
					if (result != null) {
						return result;
					}
				}
				try {
					in.closeEntry();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
